import { getPatientList } from '@/services/order/api';
import { addPatientInfo, editPatientInfo } from '@/services/patient/patientApi';
import { showMsg } from '@/utils/utils';
import { ModalForm, ProFormText } from "@ant-design/pro-form";
import { Button, FormInstance, Spin } from 'antd';
import { useEffect, useRef, useState } from 'react';

const EditModal = (props: EditModalProps) => {

  const { open, onOpenChange, rowData } = props;

  const formRef = useRef<FormInstance>();
  const [showId, setShowId] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);

  const queryPatientInfo = async () => {
    const identity = formRef.current?.getFieldValue('identity_no');
    if (!identity)
      return;
    try {
      setLoading(true);
      const res = await getPatientList({ identity_no: identity });
      if (res && res.length !== 0) {
        const { patient_id, patient_name, mobile } = res[0];
        console.info(patient_id, patient_name, mobile);
        formRef.current?.setFieldsValue({
          patient_id, patient_name, mobile
        });
        if (patient_id) {
          setShowId(true);
        }
      }
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (rowData) {
      formRef.current?.setFieldsValue(rowData);
    }
    if (rowData?.patient_id) {
      setShowId(true);
    }
  }, [rowData]);

  const save = async (values: FormType) => {
    try {
      if (rowData) {
        await editPatientInfo({ ...values, record_id: rowData.record_id });
        showMsg('修改成功', 'success');
      } else {
        await addPatientInfo({ ...values });
        showMsg('新增成功', 'success');
      }
      onOpenChange?.(false);
    } catch (reason: any) {
      showMsg(reason.data?.errmsg || '保存失败');
    }
  };

  return <>
    <ModalForm<FormType>
      title="新增/编辑患者信息"
      formRef={formRef}
      width={500}
      className='editModal'
      layout="horizontal"
      modalProps={{ okText: "保存", maskClosable: false, destroyOnClose: true }}
      onVisibleChange={visible => { if (!visible) { setShowId(false); } onOpenChange(visible); }}
      visible={open}
      labelAlign="right"
      onFinish={save}
    >
      <Spin spinning={loading}>
        <ProFormText label="患者身份证" name="identity_no" labelCol={{ flex: '0 0 110px' }}
          rules={[{ required: true }]} wrapperCol={{ span: 16 }}
          addonAfter={<Button type="primary" onClick={queryPatientInfo}>查询</Button>}
        />
        <ProFormText label="患者编号" name="patient_id" labelCol={{ flex: '0 0 110px' }} wrapperCol={{ span: 16 }} hidden={!showId} readonly required />
        <ProFormText label="患者姓名" name="patient_name" labelCol={{ flex: '0 0 110px' }} wrapperCol={{ span: 16 }} rules={[{ required: true }]} />
        <ProFormText label="患者手机号" name="mobile" labelCol={{ flex: '0 0 110px' }} wrapperCol={{ span: 16 }} rules={[{ required: true }]} />
      </Spin>
    </ModalForm>
  </>;
};

type FormType = Pick<PERMISSIONSAPI.SubDept, 'sub_dept_name' | 'address' | 'status' | 'manager_oper_id'>;

interface EditModalProps {
  open: boolean,
  onOpenChange: (open: boolean) => void,
  rowData?: PATIENT.PatientInfo
}

export default EditModal;
